/**
 * Created by jiexin on 2017/11/21.
 */
layui.use(['layer', 'table','form', 'element'], function() {
    var layer = layui.layer;//弹层
    var table = layui.table; //表格
    var $ = layui.jquery;
    var form = layui.form;
    var element = layui.element; //元素操作

    //select允许输入
    var module_name;
    $("#module_name_select").on("click", function () {
        var $obj = $(this).find("input");
        $obj.off('blur');
        $obj.on('blur', function(){
            module_name = $(this).val();
            $("#module_name").val(module_name)
            // $(".perlist").append('<option value="10000">' + group_list[i]["group_name"] + '</option>');

        })
    });

    //select重载
    form.on('select(system_type_one)', function (sodata) {
        addoptionO(sodata.value, "one")
    });

    form.on('select(system_type_two)', function (stdata) {
        addoptionO(stdata.value, "two")
    });


    function addoptionO(sid, ssel) {
        if (sid === '1'){
            var select_list = sel_win;
            if (ssel === "one"){
                var s_mode = "module_name_one";
                var $sbj = $("#module_name_one");
                addoptionT(s_mode, $sbj, select_list)
            }else if (ssel === "two"){
                var s_mode = "module_name_select";
                var $sbj = $("#module_name_two");
                addoptionT(s_mode, $sbj, select_list)
            }
        }else if (sid === '2') {
            var select_list = sel_linux;
            if (ssel === "one"){
                var s_mode = "module_name_one";
                var $sbj = $("#module_name_one");
                addoptionT(s_mode, $sbj, select_list)
            }else if (ssel === "two"){
                var s_mode = "module_name_select";
                var $sbj = $("#module_name_two");
                addoptionT(s_mode, $sbj, select_list)
            }
        }
    }

    function addoptionT(ts_mode, tsbj, ts_list) {
        tsbj.find("option.add-select").remove();
        for (var i=0; i < ts_list.length; i++) {
            tsbj.append('<option value="'+ i + '" class="add-select">' + ts_list[i] + '</option>');
        }
        // form.render('select', ts_mode);
        form.render('select');
    }

    //查询
    var filter_data = [];
    form.on('submit(query_sel)', function () {
        var sel_ab_data = $("#abnormal_paper_div").val();
        var new_table = [];
        try
            {
                var sel_module_name = $("#module_name_one_div").find(".layui-this")[0]["childNodes"][0]["data"];
                for (var i=0; i<table_data.length; i++){
                    if (table_data[i]["module_name"] === sel_module_name){
                        if (sel_ab_data !== "") {
                            if (table_data[i]["abnormal_paper"].indexOf(sel_ab_data) >= 0) {
                                new_table.push(table_data[i])
                            }
                        }else {
                            new_table.push(table_data[i]);
                        }
                    }
                }

                statistable.reload({
                    data:new_table
                })
            }
        catch(err)
            {
                try
                    {
                        var sel_module_sys_name = $("#module_name_div").find(".layui-this")[0]["childNodes"][0]["data"];
                        console.log(sel_module_sys_name, 111111111111111);
                        for (var x=0; x<table_data.length; x++){
                            console.log(table_data[x]["system_type"]);
                            if (table_data[x]["system_type"] === sel_module_sys_name){
                                if (sel_ab_data !== "") {
                                    if (table_data[x]["abnormal_paper"].indexOf(sel_ab_data) >= 0) {
                                        new_table.push(table_data[x])
                                    }
                                }else {
                                    new_table.push(table_data[x]);
                                }
                            }
                        }
                        statistable.reload({
                            data:new_table
                        })
                    }
                catch(err)
                    {
                        if (sel_ab_data !== ""){
                            for (var n=0; n<table_data.length; n++){
                                if (table_data[n]["abnormal_paper"].indexOf(sel_ab_data) >= 0 ){
                                    new_table.push(table_data[n])
                                }
                            }
                            statistable.reload({
                                data:new_table
                            })
                        }else {
                            statistable.reload({
                                data:table_data
                            })
                        }
                    }


            }
        if (new_table.length > 0){
            filter_data = new_table;
            console.log(filter_data,1111)
        }
    });

    $("#sel_resets").on('click', function () {
        filter_data = [];
        statistable.reload({
            data:table_data
        })
    });


    $("#excelsubmit").on('click', function () {
        var exe_data;
        if (filter_data.length > 0){
            exe_data = {"data": JSON.stringify(filter_data), "type":0};
            console.log(filter_data,2222)
        }else {
            exe_data = {"type":1}
        }
        var excelname1 = "/static/" + 'abnormal.xlsx';
        var excelname2 = 'abnormal.xlsx';
        var $obj = $("#excelname");
        $obj.attr("href", excelname1);
        $.ajax({
            url:"/ab-statistical-excel/",
            dataType: "json",
            type: "POST",
            data: exe_data,
            async: false,
            success: function (ex_data) {
                $obj.attr("download", excelname2);
                layer.msg('下载数据');
            }
        })
    });

    // form.on('select(module_name)', function (sdata) {
    //     console.log(sdata.value);
    //     if (sdata.value === '1000'){
    //         $("#module_name_select").find(".layui-form-select").css('display','none');
    //         $("#module_name_input").css('display','block')
    //     }
    // });
    //
    // $("#resets").on("click",function () {
    //     $("#module_name_select").find(".layui-form-select").css('display','block');
    //     $("#module_name_input").css('display','none')
    // });


    form.on('submit(absubmit)', function (data) {
        var add_data = data.field;
        delete add_data["module_name_select"];
        $.ajax({
            url: '/ab-statistical-add/',
            type: 'POST',
            dataType: 'json',
            data: {"adddata": JSON.stringify(add_data)},
            success: function (ad_return_data) {
                if (ad_return_data["status"] === 0){
                    $("#resets").trigger('click');
                    $("#module_name_select").find(".layui-form-select").css('display','block');
                    $("#module_name_input").css('display','none');
                    table_data = ad_return_data["table_data"];
                    sel_linux = ad_return_data["sel_linux"];
                    sel_win = ad_return_data["sel_win"];
                    statistable.reload({
                        data: table_data
                    })

                }else {
                    layer.msg("添加失败！")
                }

            }
        })
    });



    var ab_a = document.getElementById("ab-left");
    var ab_h = ab_a.offsetHeight - 90;
    console.log(ab_h);


    var table_format_ablist = [[
         {field: 'system_type', align: 'center', title: '系统类型', width: '13%'}
         , {field: 'module_name', align: 'center', title: '模块名称', width: '18%'}
         , {field: 'abnormal_paper', title: '异常简述', width: '23%'}
         , {field: 'number', align: 'center', title: '次数', width: '10%', sort:true}
         , {field: 'ip_addr', align: 'center', title: '服务器名', width: '16%'}
         , {field: 'createDate', align: 'center', title: '创建时间', width: '18%'}
         , {fixed: 'right',width: '23%', align: 'center',  title: '操作', toolbar: '#absDemo'}
    ]];

    $('.layui-table-ablist').each(function() {
        //获取标签对于的一个属性
        var $obj = $(this);
        var tableid = $obj[0].id;
        var etaleid = '#' + tableid;
        var toolid = 'tool(' + tableid + ')';
        createtable(etaleid,tableid,table_data,table_format_ablist, ab_h);
        statistool(toolid,tableid);
    });

    var statistable;
    function createtable(etaleid,tableid,datas,table_format,table_height) {
        statistable = table.render({
            elem: etaleid,
            id: tableid,
            //url: '/demo/table/user/',
            // width: 440,
            height: table_height,
            limit: 10,
            page: true,
            data: datas,
            cols: table_format
        });
    }

    var select_data;
    var add_id;
    function statistool(toolid, tableid) {
        //监听工具条
        //注：tool是工具条事件名，test是table原始容器的属性 lay-filter="对应的值"
        table.on(toolid, function (obj) {
            var data = obj.data; //获得当前行数据
            var layEvent = obj.event; //获得 lay-event 对应的值
            // var tr = obj.tr; //获得当前行 tr 的DOM对象
            var checkStatus = table.checkStatus(tableid);
            // console.log(data);
            //tr.index()
            if (layEvent === 'check') {
                $(".ab-right-two").css("display", "block");
                add_id = data["id"];
                var name_list = ["system_type", "module_name", "abnormal_paper", "abnormal_des", "solution", "number"];
                var n = 0;
                $('.statis-span-data').each(function() {
                    $(this).text(data[name_list[n]]);
                    n++;
                });
            } else if (layEvent === 'modify'){
                $(".ab-right-two").css("display", "none");
                select_data = data;
                $(".form-item-select").addClass("layui-hide");
                $("#absubmit").addClass("layui-hide");
                $("#resets").addClass("layui-hide");
                $("#abmodify").removeClass("layui-hide");
                $("#cancel").removeClass("layui-hide");
                $("#system_two").removeAttr("lay-verify", "required");
                $("#module_name").removeAttr("lay-verify", "required");
                $("#ip_addr").val(data["ip_addr"]);
                $("#abnormal_paper").val(data["abnormal_paper"]);
                $("#abnormal_des").val(data["abnormal_des"]);
                $("#solution").val(data["solution"]);

            } else if(layEvent === 'delete'){
                var T_data = {"data": data["id"], "type": 0};
                var Tm_data = {"data": JSON.stringify({}), "id":1, "type": 1};
                $(".ab-right-two").css("display", "none");
                abajaxTwo(T_data);
                abajaxTwo(Tm_data);
            }
        });
    }

    $("#cancel").on('click', function () {
        $(".form-item-select").removeClass("layui-hide");
        $("#absubmit").removeClass("layui-hide");
        $("#resets").removeClass("layui-hide");
        $("#abmodify").addClass("layui-hide");
        $("#cancel").addClass("layui-hide");
        $("#system_two").addClass("lay-verify", "required");
        $("#module_name").addClass("lay-verify", "required");
        // $("#ip_addr").val();
        // $("#abnormal_paper").val();
        // $("#abnormal_des").val();
        // $("#solution").val();
    });

    form.on('submit(abmodify)', function (data) {
        var mod_data = data.field;

        var new_mod_data = {};
        $.each(mod_data, function (k, v) {
            if (v !== ""){
                if (select_data[k] !== v){
                    new_mod_data[k] = v
                }
            }
        });

        var return_mod_data = {"data": JSON.stringify(new_mod_data), "id":select_data["id"], "type": 1};
        abajaxTwo(return_mod_data)
    });

    function abajaxTwo(Tdata) {
        $.ajax({
            url: '/ab-statistical-ops/',
            dataType: 'json',
            type: 'POST',
            data:Tdata,
            success: function (Treturn_data) {
                if (Treturn_data["type"] === 0){
                    // if (Treturn_data["status"] === 0){
                    table_data = Treturn_data["table_data"];
                    sel_linux = Treturn_data["sel_linux"];
                    sel_win = Treturn_data["sel_win"];
                    console.log(table_data);
                    statistable.reload({
                        data:table_data
                    })
                    // }
                } else if (Treturn_data["type"] === 1) {
                    table_data = Treturn_data["table_data"];
                    $(".form-item-select").removeClass("layui-hide");
                    $("#absubmit").removeClass("layui-hide");
                    $("#resets").removeClass("layui-hide");
                    $("#abmodify").addClass("layui-hide");
                    $("#cancel").addClass("layui-hide");
                    $("#system_two").attr("lay-verify", "required");
                    $("#module_name").attr("lay-verify", "required");
                    $("#resets").trigger("click");
                    statistable.reload({
                        data:table_data
                    })
                } else if (Treturn_data["type"] === 2) {
                    table_data = Treturn_data["table_data"];
                    statistable.reload({
                        data:table_data
                    })
                }else {
                    layer.msg("操作失败")
                }


            }
        })
    }

    $("#sum_add").on("click", function () {
        var add_data = {"id":add_id, "type":2};
        abajaxTwo(add_data);
        var num = parseInt($("#num_data").text()) + 1 ;
        console.log(num);
        $("#num_data").text(num)
    });

    $("#sum_return").on("click", function () {
        $(".ab-right-two").css("display", "none");
    });




    $('.demoTable .layui-btn').on('click', function() {
        var type = $(this).data('type');
        active[type] ? active[type].call(this) : '';
    });
});